/*
 * Copyright 2012 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.vitaliyl.monitoring.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.vitaliyl.monitoring.server.beans.MessageDescriptor;
import org.vitaliyl.monitoring.server.beans.ServerDescriptor;
import org.vitaliyl.monitoring.server.dao.AMessageDAO;
import org.vitaliyl.monitoring.server.dao.AServerDescriptorDAO;

import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;
import com.google.appengine.api.taskqueue.TaskOptions.Method;
import com.google.gson.Gson;

/**
 * Servlet that adds display number of devices and button to send a message.
 * <p>
 * This servlet is used just by the browser (i.e., not device) and contains the
 * main page of the demo app.
 */
@SuppressWarnings("serial")
public class CheckerServlet extends BaseServlet {

	static final String ATTRIBUTE_STATUS = "status";

	static final Pattern ACTIVE_CONNECTIONS_PATTERN = Pattern.compile("Active connections: (\\d+)");

	/**
	 * Displays the existing messages and offer the option to send a new one.
	 */
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		resp.setContentType("application/json");

		logger.fine("CheckerServlet fired!");

		List<MessageDescriptor> statusList = new ArrayList<MessageDescriptor>();
		List<ServerDescriptor> servers = AServerDescriptorDAO.getServerDescriptors();

		for (int i = 0; i < servers.size(); i++) {

			MessageDescriptor md = new MessageDescriptor(servers.get(i));
			try {
				String rawContent = getRawContent(md.getServerUrl());
				Matcher m = ACTIVE_CONNECTIONS_PATTERN.matcher(rawContent);
				if (m.find()) {
					md.setCurrentConnections(Integer.parseInt(m.group(1)));
				}
			} catch (IOException e) {
				md.setDown(true);
			}
			statusList.add(md);
			if (md.hasProblem()) {
				md.setWhen(new Date());
				String key = AMessageDAO.createMessageDescriptor(md);

				Queue queue = QueueFactory.getQueue("serverError");
				TaskOptions taskOptions = TaskOptions.Builder.withUrl("/sendAll").param(SendMessageServlet.PARAMETER_SERVER, key).method(Method.POST);
				queue.add(taskOptions);
			}
		}

		writeStatusListToResponse(resp, statusList);

		resp.setStatus(HttpServletResponse.SC_OK);
	}

	private void writeStatusListToResponse(HttpServletResponse resp, List<MessageDescriptor> list) throws IOException {
		Gson gson = new Gson();
		PrintWriter writer = resp.getWriter();
		writer.print(gson.toJson(list));
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		doGet(req, resp);
	}

	public static String getRawContent(String url) throws IOException {
		URL website = new URL(url);
		URLConnection connection = website.openConnection();
		BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

		StringBuilder response = new StringBuilder();
		String inputLine;

		while ((inputLine = in.readLine()) != null)
			response.append(inputLine);

		in.close();

		return response.toString();
	}

}
